﻿using Microsoft.AspNetCore.SignalR;
using System.Api.Read.HubClients;
using System.Api.Read.HubService;

namespace System.Api.Read.Hubs
{
    /// <summary>
    /// 集线器
    /// </summary>
    public class ChatHub : Hub<IChatClient>
    {
        ILogger<ChatHub> logger;
        readonly CommonService _common;
        public ChatHub(ILogger<ChatHub> logger)
        {
            this.logger = logger;
        }
        /// <summary>
        /// 客户端连接服务端
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            var id = Context.ConnectionId;
            logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Connection Server！");
            return base.OnConnectedAsync();
        }
        /// <summary>
        /// 客户端断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception? exception)
        {
            var id = Context.ConnectionId;
            logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Close Connection Server!");
            return base.OnDisconnectedAsync(exception);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        // 定义了 SendMessage 方法,客户端可以调用该方法
        public async Task SendMessage(string user, string message)
        {
            Console.WriteLine("Have one Data!" + message);
            await Clients.All.SendMessage(_common.SendMessage(message));
        }
    }

}
